import { env } from "~/env";

import { type Message } from "../messaging";
import { fetchStream } from "../sse";

import { type TeamMember, type ChatEvent } from "./types";

export function chatStream(
  userMessage: Message,
  state: { messages: { role: string; content: string }[] },
  params: {
    deepThinkingMode: boolean;
    searchBeforePlanning: boolean;
    teamMembers: string[];
    articlePrompt?: {
      style: string;
      title: string;
      content: string;
      host: string;
    };
  },
  options: { abortSignal?: AbortSignal } = {},
) {
  return fetchStream<ChatEvent>(
    (env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000/api") + "/chat/stream",
    {
      body: JSON.stringify({
        messages: [
          ...state.messages
            .filter((msg, i, arr) => {
              // Only include complete rounds (pairs of messages)
              if (i === 0) return true; // Always include first message
              return arr[i-1]?.role !== msg.role;
            })
            .slice(-6), // Keep last 3 complete rounds (6 messages)
          userMessage
        ],
        deep_thinking_mode: false,
        search_before_planning: false,
        debug:false,
        team_members: params.teamMembers,
        article_prompt: params.articlePrompt ? {
          style: params.articlePrompt.style,
          title: params.articlePrompt.title, 
          content: params.articlePrompt.content,
          host: params.articlePrompt.host
        } : undefined
      }),
      signal: options.abortSignal,
    },
  );
}

export async function queryTeamMembers() {
  const response = await fetch(
    (env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000/api") + "/team_members",
    { method: "GET" },
  );
  const { team_members } = (await response.json()) as {
    team_members: Record<string, TeamMember>;
  };
  const allTeamMembers = Object.values(team_members);
  return [
    ...allTeamMembers.filter((member) => !member.is_optional),
    ...allTeamMembers.filter((member) => member.is_optional),
  ];
}
